// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let fileContent = event.fileContent;
  let custom = event.custom;
  let card_url = event.card_url;
  let card_num = event.card_num;
  let card_id_num = event.card_id_num;
  let card_pwd_num = event.card_pwd_num;
  let goods_id = event.goods_id;
  let goods_number = event.goods_number;
  let expiration_date = new Date(event.expiration_date);
  let openid = wxContext.OPENID;
  let i = 0;
  let counter = 100;
  let cloudPath = "card_image/" + openid + Date.now() + ".png";
  let update_time = new Date();
  var card_array = [];
  let temp_obj = new Object();
  let fileID = '';
  if (custom == false) {
    fileID = card_url;
  } else {
    let res = await cloud.uploadFile({
      cloudPath: cloudPath,
      fileContent: new Buffer(fileContent, 'base64'),
    });
    fileID = res.fileID;
  }
  for (i; i < card_num; i++) {
    // 生成卡号和密码
    let card_id = new Date().getTime().toString().substring(13 - card_id_num, 10) + counter;
    let res = await cloud.callFunction({
      name: 'ToolFunctions',
      data: {
        type: 'randomString',
        randomFlag: false,
        min: card_pwd_num
      }
    });
    let card_pwd = res.result;
    // 生成小程序码
    let res2 = await cloud.callFunction({
      name: 'ToolFunctions',
      data: {
        type: 'getMiniProgramCode',
        card_id: card_id,
        card_pwd: card_pwd
      }
    });
    let qrcode_url = res2.result;
    // 存入临时对象
    temp_obj.Issuer_openid = openid;
    temp_obj.goods_id = goods_id;
    temp_obj.goods_number = goods_number;
    temp_obj.card_number = card_id;
    temp_obj.card_password = card_pwd;
    temp_obj.qrcode_url = qrcode_url;
    temp_obj.card_url = fileID;
    temp_obj.expiration_date = expiration_date;
    temp_obj.update_time = update_time;
    temp_obj.status = 1;
    // 连接数组
    card_array = card_array.concat(temp_obj);
    // 计数器自增，临时对象重置
    counter += 1;
    temp_obj = {};
    console.log(card_array);
  }
  console.log('updateCards将卡券信息写入数据库'),
    // 将卡券信息写入数据库
    db.collection('ops_card').add({
      data: card_array,
    })
}